// HTTP请求工具类
import { ElMessage } from 'element-plus'
import { API_CONFIG } from '../config/api'
import { logger } from '../config/env'

// 请求参数接口
interface RequestOptions {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  headers?: Record<string, string>
  body?: any
  params?: Record<string, any>
}

// 响应数据接口
interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
}

// HTTP请求类
class HttpClient {
  private baseURL: string

  constructor(baseURL: string = API_CONFIG.BASE_URL) {
    this.baseURL = baseURL
  }

  // 构建URL（包含查询参数）
  private buildUrl(url: string, params?: Record<string, any>): string {
    const fullUrl = url.startsWith('http') ? url : `${this.baseURL}${url}`
    
    if (!params) return fullUrl
    
    const searchParams = new URLSearchParams()
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null) {
        searchParams.append(key, String(value))
      }
    })
    
    const queryString = searchParams.toString()
    return queryString ? `${fullUrl}?${queryString}` : fullUrl
  }

  // 获取请求头
  private getHeaders(customHeaders?: Record<string, string>): Record<string, string> {
    const defaultHeaders: Record<string, string> = {
      'Content-Type': 'application/json'
    }

    // 添加认证token（如果存在）
    const token = localStorage.getItem('token')
    if (token) {
      defaultHeaders['Authorization'] = `Bearer ${token}`
    }

    return { ...defaultHeaders, ...customHeaders }
  }

  // 处理响应
  private async handleResponse<T>(response: Response): Promise<T> {
    try {
      // 检查HTTP状态码
      if (!response.ok) {
        throw new Error(`HTTP Error: ${response.status} ${response.statusText}`)
      }

      const responseData = await response.json()
      
      // 检查是否是标准的ApiResponse格式 {code, message, data}
      if (responseData && typeof responseData === 'object' && 'code' in responseData && 'data' in responseData) {
        const apiResponse = responseData as ApiResponse<T>
        // 检查业务状态码
        if (apiResponse.code === 200) {
          return apiResponse.data
        } else {
          throw new Error(apiResponse.message || '请求失败')
        }
      }
      
      // 如果不是标准格式，直接返回原始数据
      return responseData as T
      
    } catch (error) {
      // 处理JSON解析错误或网络错误
      if (error instanceof Error) {
        ElMessage.error(error.message)
        throw error
      } else {
        const errorMessage = '网络请求失败'
        ElMessage.error(errorMessage)
        throw new Error(errorMessage)
      }
    }
  }

  // 通用请求方法
  async request<T = any>(url: string, options: RequestOptions = {}): Promise<T> {
    const {
      method = 'GET',
      headers,
      body,
      params
    } = options

    const requestUrl = this.buildUrl(url, params)
    const requestHeaders = this.getHeaders(headers)

    const config: RequestInit = {
      method,
      headers: requestHeaders,
      // 添加请求超时
      signal: AbortSignal.timeout(API_CONFIG.TIMEOUT)
    }

    // 添加请求体（非GET请求）
    if (method !== 'GET' && body) {
      config.body = JSON.stringify(body)
    }

    // 记录请求日志
    logger.debug(`${method} ${requestUrl}`, { body, params })

    try {
      const response = await fetch(requestUrl, config)
      const result = await this.handleResponse<T>(response)
      
      // 记录响应日志
      logger.debug(`${method} ${requestUrl} - Success`, result)
      
      return result
    } catch (error) {
      // 记录错误日志
      logger.error(`${method} ${requestUrl} - Error`, error)
      
      // 网络错误处理
      if (error instanceof TypeError) {
        ElMessage.error('网络连接失败，请检查网络设置')
        throw new Error('网络连接失败')
      }
      
      // 超时错误处理
      if (error instanceof DOMException && error.name === 'TimeoutError') {
        ElMessage.error('请求超时，请稍后重试')
        throw new Error('请求超时')
      }
      
      throw error
    }
  }

  // GET请求
  async get<T = any>(url: string, params?: Record<string, any>, headers?: Record<string, string>): Promise<T> {
    return this.request<T>(url, { method: 'GET', params, headers })
  }

  // POST请求
  async post<T = any>(url: string, body?: any, headers?: Record<string, string>): Promise<T> {
    return this.request<T>(url, { method: 'POST', body, headers })
  }

  // PUT请求
  async put<T = any>(url: string, body?: any, headers?: Record<string, string>): Promise<T> {
    return this.request<T>(url, { method: 'PUT', body, headers })
  }

  // DELETE请求
  async delete<T = any>(url: string, headers?: Record<string, string>): Promise<T> {
    return this.request<T>(url, { method: 'DELETE', headers })
  }
}

// 创建默认的HTTP客户端实例
export const http = new HttpClient()

// 导出HTTP客户端类
export { HttpClient }
export type { RequestOptions, ApiResponse }